// 匹配结果页面的JavaScript逻辑

document.addEventListener('DOMContentLoaded', function() {
    console.log('匹配结果页面已加载');
    
    // 加载匹配结果数据
    loadMatchingResults();
});

// 加载匹配结果数据
async function loadMatchingResults() {
    try {
        showLoading(true);
        
        // 从API获取匹配结果数据
        const results = await apiRequest('/results');
        
        // 更新UI
        updateSummaryPanel(results.summary);
        updateShipmentsTable(results.shipments_allocation);
        updateUtilizationChart(results.routes_utilization);
        drawAllocationMap(results.shipments_allocation);
        
        showLoading(false);
    } catch (error) {
        console.error('加载匹配结果失败:', error);
        showError('加载匹配结果失败: ' + error.message);
        showLoading(false);
    }
}

// 更新总体统计面板
function updateSummaryPanel(summary) {
    document.getElementById('total-shipments').textContent = summary.total_shipments;
    document.getElementById('total-capacity').textContent = summary.total_capacity;
    
    const matchingRate = summary.total_shipments > 0 ? 
        Math.round((summary.matched_shipments / summary.total_shipments) * 100) : 0;
    document.getElementById('matching-rate').textContent = matchingRate + '%';
    
    document.getElementById('stability').textContent = summary.stability ? '稳定' : '不稳定';
    document.getElementById('execution-time').textContent = summary.execution_time + '秒';
}

// 更新货物分配表格
function updateShipmentsTable(shipments) {
    const tbody = document.querySelector('#shipments-table tbody');
    tbody.innerHTML = '';
    
    shipments.forEach(shipment => {
        const row = document.createElement('tr');
        
        row.innerHTML = `
            <td>${shipment.shipment_id}</td>
            <td>${shipment.origin}</td>
            <td>${shipment.destination}</td>
            <td>${shipment.assigned_route}</td>
            <td>${shipment.cost}</td>
            <td>${shipment.preference_rank}</td>
            <td>${shipment.assigned_route === 'Self' ? '未分配' : '已分配'}</td>
        `;
        
        tbody.appendChild(row);
    });
}

// 更新路线利用率图表
function updateUtilizationChart(routes) {
    const chartContainer = document.getElementById('utilization-chart');
    chartContainer.innerHTML = '<h4 style="text-align:center;margin-top:20px;">路线利用率</h4>';
    
    // 准备图表数据
    const chartData = routes.map(route => ({
        label: route.route_id,
        value: route.utilization_rate
    }));
    
    // 创建并绘制柱状图
    const chart = new SimpleChart('utilization-chart');
    chart.drawBarChart(chartData, {
        barColor: '#3498db',
        labelColor: '#2c3e50',
        valueColor: '#7f8c8d'
    });
}

// 绘制货物分配地图
function drawAllocationMap(shipments) {
    const mapContainer = document.getElementById('map-container');
    mapContainer.innerHTML = ''; // 清空容器
    
    // 创建地图容器
    const map = document.createElement('div');
    map.className = 'allocation-map';
    map.style.cssText = 'width: 100%; height: 100%; position: relative;';
    
    // 创建节点和连接线（简化版可视化）
    const nodes = new Set();
    const links = [];
    
    // 收集所有节点和连接
    shipments.forEach(shipment => {
        nodes.add(shipment.origin);
        nodes.add(shipment.destination);
        
        if (shipment.assigned_route !== 'Self') {
            links.push({
                source: shipment.origin,
                target: shipment.destination,
                route: shipment.assigned_route
            });
        }
    });
    
    // 创建节点元素
    const nodeList = Array.from(nodes);
    nodeList.forEach((node, index) => {
        const nodeElement = document.createElement('div');
        nodeElement.className = 'node';
        nodeElement.textContent = node;
        nodeElement.style.cssText = `
            position: absolute;
            width: 40px;
            height: 40px;
            background-color: #2ecc71;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 12px;
            top: ${(index % 5) * 20}%;
            left: ${(Math.floor(index / 5) % 3) * 30}%;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        `;
        map.appendChild(nodeElement);
    });
    
    // 创建连接线元素
    links.forEach((link, index) => {
        const line = document.createElement('div');
        line.className = 'link';
        line.style.cssText = `
            position: absolute;
            height: 2px;
            background-color: #3498db;
            transform-origin: 0 0;
            top: 20%;
            left: 10%;
            width: 100px;
        `;
        map.appendChild(line);
    });
    
    // 添加说明文字
    const info = document.createElement('div');
    info.textContent = '货物分配地图 (简化版)';
    info.style.cssText = 'position: absolute; bottom: 10px; left: 10px; color: #7f8c8d; font-size: 14px;';
    map.appendChild(info);
    
    mapContainer.appendChild(map);
}

// 显示加载状态
function showLoading(show) {
    // 可以在这里实现加载动画
    if (show) {
        console.log('正在加载数据...');
    } else {
        console.log('数据加载完成');
    }
}

// 显示错误信息
function showError(message) {
    console.error(message);
    // 可以在这里实现错误提示UI
}